<template>
  <div class="body">
    <div class="table_filtrate">
      <div class="tf_item" style="margin-right: 30px">
        <div class="tag">搜索</div>
        <el-input v-model="tableParams.fuzzy_search" class="input_fuzzy_search input" size="mini" placeholder="ID|名字"
          clearable />
      </div>

      <div class="tf_item" style="margin-right: 30px">
        <el-date-picker v-model="tableParams.time_interval" size="mini" type="daterange" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" value-format="timestamp" />
      </div>

      <div class="tf_item" style="margin-right: 30px">
        <div class="tag">数据类型</div>
        <el-select v-model="tableParams.stat_data_type" class="input" placeholder="请选择" size="mini">
          <el-option label="全部" value="all" />
          <el-option label="有效数据" value="valid_data" />
        </el-select>
      </div>

      <div class="tf_item">
        <el-button type="primary" plain size="mini" @click="search">搜索</el-button>
      </div>
    </div>
    <div class="table_operate">
      <div class="tool-self">
        <el-button class="btn_export" type="info" size="mini" @click="exportExcelFun()">导出<i
            class="el-icon-download el-icon--right" /></el-button>
      </div>
    </div>

    <div class="table-card">
      <el-table  id="table_id" v-loading="loading.table" class="table" :data="tableData.data" :row-class-name="tableRowClassName"
        :border="true" size="mini" show-summary :summary-method="$_App_getSummaries"
                 @sort-change="handleSortChange">
        <el-table-column prop="date" label="日期" width="90" />
        <el-table-column prop="channel_id" label="渠道ID" width="80" />
        <el-table-column prop="channel_name" label="渠道名字" width="120" />
        <el-table-column prop="organization_earnings_real" width="95" label="机构收益" sortable="custom"/>
        <el-table-column prop="cost_real" label="渠道成本" width="95" sortable="custom"/>
        <el-table-column prop="earnings_real" label="渠道收益" width="95" sortable="custom"/>
        <el-table-column prop="profit" label="利润" width="80" sortable="custom"/>
        <el-table-column prop="good_rate" label="优质率" width="85" sortable="custom"/>
        <el-table-column prop="call_completing_rate" label="接通率" width="85" sortable="custom"/>
        <el-table-column prop="roi" label="ROI" width="75" sortable="custom"/>
        <el-table-column prop="pv" label="PV数" width="75" sortable="custom"/>
        <el-table-column prop="uv_num" label="UV数" width="75" sortable="80"/>
        <el-table-column prop="channel_cooperative_price" label="合作价格" width="95" sortable="custom"/>
        <el-table-column prop="clue_num" label="线索总量" width="95" sortable="custom"/>
        <el-table-column prop="clue_register_num" label="注册数" width="85" sortable="custom"/>
        <el-table-column prop="clue_register_rate" label="注册率" width="85" sortable="custom"/>
        <el-table-column label="表单数" width="85" sortable="custom">
          <template slot-scope="scope">
            <div v-if="scope.row.channel_calculation_type == 'cpa'">
              <span style="color: #212121">{{ scope.row.clue_form_num }}</span>
              <span>/</span>
              <span style="color: #616161">{{
                scope.row.clue_form_num_deduction
              }}</span>
            </div>
            <div v-else>
              <span style="color: #212121">{{ scope.row.clue_form_num }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="clue_form_rate" label="表单率" width="85" sortable="custom">
          <template slot-scope="scope">
            <span>{{ scope.row.clue_form_rate }}%</span>
          </template>
        </el-table-column>
        <el-table-column label="类型" width="120">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.channel_calculation_type == 'joint_climb'" size="mini">联登</el-tag>
            <el-tag v-else size="mini">{{ scope.row.channel_calculation_type }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="advertising_visits_num" label="贷超点击数" width="110" sortable="custom"/>
        <el-table-column prop="advertising_visits_price" label="贷超收益" width="95" sortable="custom"/>
        <el-table-column prop="clue_push_success_num" label="推送成功数" width="110" sortable="custom"/>
        <el-table-column prop="clue_push_success_rate" label="推送成功率" width="110" sortable="custom"/>

        <el-table-column prop="api_collision_count" label="api撞库" width="95" sortable="custom"/>
        <el-table-column prop="api_push_count" label="api进件" width="95" sortable="custom"/>
        <el-table-column label="更新时间" width="140">
            <template slot-scope="scope">
              <div>{{ scope.row.updatetime }}</div>
            </template>
          </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-link v-show="scope.row.status == 'stop'" class="handle" type="warning"
              @click="handleTableRegain(scope.$index, scope.row)">恢复</el-link>
            <el-link v-show="scope.row.status == 'normal'" class="handle" type="primary"
              @click="handleTableEdit(scope.$index, scope.row)">编辑</el-link>
            <el-link v-show="scope.row.status == 'normal'" class="handle" type="danger"
              @click="handleTableDelete(scope.$index, scope.row)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination :current-page="currentPage4" :page-sizes="$pageSize" :page-size="tableParams.size"
        layout="total, sizes, prev, pager, next, jumper" :total="tableData.total" @size-change="handleTableSizeChange"
        @current-change="handleTableCurrentChange" />
    </div>
  </div>
</template>

<script>
import { apiDashboardChannellistpage } from '@/api/apiCommon'

import { paramsDeleteNull } from '@/utils/common'
import { formatTimestamp,dateToTimestamp } from '@/utils/datetimeUtil'
import { exportExcel } from '@/utils/htmlToExcelUtils'
export default {
  name: 'Index',
  data() {
    return {
      tableParams: {
        page: 1,
        size: 100,
        fuzzy_search: '',
        stat_data_type: 'valid_data',
        time_interval: [new Date(), new Date()]
      },
      tableData: {
        current_page: 1,
        data: [],
        last_page: 1,
        per_page: '15',
        total: 0
      },
      currentPage4: 1,
      business_select: [],
      organization_select: [],
      fromViewCofing: {
        input_width: '120px',
        label_width: '120px'
      },
      loading: {
        table: false
      }
    }
  },
  created() {
    this.loadTableData()
  },
  methods: {
    // 排序事件
    handleSortChange({ column, prop, order }) {
      const sortedData = [...this.tableData.data];
      if (order === 'ascending') {
        sortedData.sort((a, b) => a[prop] - b[prop]);
      } else if (order === 'descending') {
        sortedData.sort((a, b) => b[prop] - a[prop]);
      }
      this.tableData = { ...this.tableData, data: sortedData };
    },
    // 导出表格
    exportExcelFun() {
      exportExcel('助贷收益统计')
    },
    // 表格搜索
    search() {
      this.tableParams.page = 1
      this.loadTableData()
    },
    // 列表请求
    loadTableData() {
      const _this = this
      _this.loading_start('table')
      var tableParamsData = { ..._this.tableParams }
      tableParamsData['initpage'] = false
      var start_date = tableParamsData['time_interval'][0]
      var end_date = tableParamsData['time_interval'][1]
      tableParamsData['start_time'] = dateToTimestamp(start_date)
      tableParamsData['end_time'] = dateToTimestamp(end_date)
      delete tableParamsData['time_interval']
      if (tableParamsData['fuzzy_search'] == '') {
        delete tableParamsData['fuzzy_search']
      }

      //   tableParamsData = paramsDeleteNull(tableParamsData, "business_uid");
      //   tableParamsData = paramsDeleteNull(tableParamsData, "o_id");
      //   tableParamsData = paramsDeleteNull(tableParamsData, "fuzzy_search");
      //   tableParamsData = paramsDeleteNull(tableParamsData, "loan_type");
      //   tableParamsData = paramsDeleteNull(tableParamsData, "push_status");
      //   tableParamsData = paramsDeleteNull(tableParamsData, "entry_status");
      apiDashboardChannellistpage(tableParamsData)
        .then((response) => {
          const result = response
          console.log(result, 'result')
          var tableData = result.data.datalist
          for (var i = 0; i < tableData.data.length; i++) {
            tableData.data[i]['updatetime'] = formatTimestamp(tableData.data[i]['updatetime'],'YYYY-MM-DD HH:mm:ss');
          }
          _this.tableData = tableData;
          _this.loading_end('table')
        })
        .catch(function (result) {
          _this.$message.error(result.msg)
          _this.tableData.data = null
          _this.loading_end('table')
        })
    },
    // 获取机构列表
    reqApiOrganization(business_uid) {
      const _this = this
      _this.loading_start('table')
      apiOrganizationSelects({
        page: 1,
        size: 99,
        business_uid: business_uid
      }).then((response) => {
        const result = response.data
        _this.organization_select = result.selects
        _this.loading_end('table')
      })
    },
    // 切换商务人员
    changeSelectBusinessuid(business_uid) {
      this.tableParams.o_id = ''
      this.reqApiOrganization(business_uid)
    },
    // 页面跳转
    handleToGoCreate() {
      this.$router.push({ path: '/product/create', query: { id: 0 } })
    },
    // 表格行状态
    tableRowClassName({ row, rowIndex }) {
      if (row['status'] == 'stop') {
        return 'discard-row'
      }
    },
    // 表格操作
    handleTableEdit(index, row) {
      this.$router.push({ path: '/product/update', query: { id: row.id } })
    },
    // 表格恢复
    handleTableRegain(index, row) {
      var _this = this
      var params = {
        id: row.id,
        status: 'normal'
      }
      _this.loading_start('table')
      apiProductUpdatePart(params).then((response) => {
        _this.loading_end('table')
        _this.loadTableData()
      })
    },
    // 表格删除
    handleTableDelete(index, row) {
      const _this = this
      _this.loading_start('table')
      apiProductDelete({
        id: row.id
      }).then((response) => {
        this.$message({
          message: response.msg,
          type: 'success'
        })
        _this.loading_end('table')
        _this.loadTableData()
      })
    },
    // 数量改变
    handleTableSizeChange(val) {
      this.tableParams.size = val
      this.loadTableData()
    },
    // 页数改变
    handleTableCurrentChange(val) {
      this.tableParams.page = val
      this.loadTableData(false)
    },
    // 部分状态改变
    tableUpdateItem(item) {
      var _this = this
      var params = {
        id: item.id,
        push_status: item.push_status,
        entry_status: item.entry_status
      }
      _this.loading_start('table')
      apiProductUpdatePart(params).then((response) => {
        _this.loading_end('table')
      })
    },
    // 加载开始...
    loading_start(keys) {
      const _this = this
      if (Array.isArray(keys)) {
        keys.forEach((key) => {
          _this.loading[key] = true
          setTimeout(() => {
            _this.loading_end(key)
          }, 2000)
        })
      } else {
        _this.loading[keys] = true
        setTimeout(() => {
          _this.loading_end(keys)
        }, 2000)
      }
    },
    // 加载结束...
    loading_end(key) {
      this.$set(this.loading, key, false) // 使用 $set 确保响应式更新
    }
  }
}
</script>

<style lang="scss"></style>
